package com.version1_4.service.implement;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.util.baidu.BaiduPush;
import com.util.baidu.MsgModelAndroid;
import com.util.baidu.MsgModelIOS;
import com.util.format.MapToJson;
import com.util.format.ReevesMap;
import com.util.format.TimeFormat;
import com.version1_4.dao.FeedDao;
import com.version1_4.dao.TopicDao;
import com.version1_4.service.FeedService;
import org.apache.commons.collections.map.HashedMap;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * Created by reeveslee on 16/5/3.
 */
@Service
public class FeedServiceImpl implements FeedService {
    private static final Logger LOGGER = Logger.getLogger(FeedServiceImpl.class);

    @Autowired
    private FeedDao feedDao;

    @Autowired
    private TopicDao topicDao;

    /**
     * 添加一个话题评论
     *
     * @param jsonObject
     * @return
     */
    @Override
    public String addFeed(JSONObject jsonObject) {
        ReevesMap result = new ReevesMap();
        // jsonObject: {"topic":,"userId":,"text":"","images":["src1","src2","src3"...],"voice":{"src":"","time":}}

        try {
            int topicId = jsonObject.getIntValue("topic");
            int userId = jsonObject.getIntValue("userId");
            String text = jsonObject.getString("text");
            JSONArray images = jsonObject.getJSONArray("images");
            String voiceString = "null";
            try {
                voiceString = jsonObject.getJSONObject("voice").toJSONString();
            } catch (Exception exception) {
                LOGGER.info("voice is null");
            }
            result.put("result", feedDao.addFeed(topicId, userId, text, images.toJSONString(), voiceString));
        } catch (Exception exception) {
            LOGGER.error("添加话题评论错误", exception);
            result.setCode(500);
            result.setInfo("Error Occurred During Analyse JsonObject");
            result.put("result", false);
        }
        return net.sf.json.JSONObject.fromObject(result).toString();
    }

    @Override
    public String replys(int feedId) {
        ReevesMap reevesMap = new ReevesMap();
        List<Map<String, Object>> replyList = feedDao.replys(feedId);
        for (Map<String, Object> reply : replyList) {
            reply.replace("voice", JSONObject.parse((String) reply.get("voice")));
            reply.replace("time", TimeFormat.convertTimeToFormat(((Date) reply.get("time")).getTime() / 1000));
        }
        reevesMap.put("replys", replyList);
        Map<String, Object> feedInfo = feedDao.feedInfo(feedId);

        if (feedInfo != null) {
            feedInfo.replace("image", JSONArray.parse((String) feedInfo.get("image")));
            feedInfo.replace("voice", JSON.parseObject((String) feedInfo.get("voice")));
            feedInfo.replace("time", TimeFormat.convertTimeToFormat(((Date) feedInfo.get("time")).getTime() / 1000));
            reevesMap.put("feedInfo", feedInfo);
        } else {
            reevesMap.setCode(500);
            reevesMap.setInfo("No Feed Information Found.");
        }
        return reevesMap.toJsonString();
    }

    @Override
    public String addReply(JSONObject jsonObject) {
        ReevesMap reevesMap = new ReevesMap();
        try {
            int userId = jsonObject.getIntValue("userId");
            int feedId = jsonObject.getIntValue("feedId");
            int subReplyTo = jsonObject.getIntValue("subReplyTo");
            String text = jsonObject.getString("text");
            String voice = "null";
            try {
                voice = jsonObject.getJSONObject("voice").toJSONString();
            } catch (Exception exception) {
                LOGGER.info("voice jsonObject is null.");
            }

            reevesMap.put("result", feedDao.addReply(userId, feedId, subReplyTo, text, voice));

            Map<String, Object> replyPushInfo = feedDao.replyPushInfo(userId, feedId, subReplyTo);
            // 给IOS用户发送消息
            MsgModelIOS msgModelIOS = new MsgModelIOS();
            msgModelIOS.setAlertStr(replyPushInfo.get("name") + "在话题中回复了你");
            msgModelIOS.put("type", "feedReply");
            msgModelIOS.put("feedId", feedId);
            BaiduPush.pushMsgToSingleDeviceIOS((String) replyPushInfo.get("baiduId"), msgModelIOS);

            // 给Android用户发送消息
            MsgModelAndroid msgModelAndroid = new MsgModelAndroid();
            msgModelAndroid.setDescription(replyPushInfo.get("name") + "在话题中回复了你");
            msgModelAndroid.custom_content.put("type", "feedReply");
            msgModelAndroid.custom_content.put("feedId", feedId);
            BaiduPush.pushMsgToSingleDeviceAndroid((String) replyPushInfo.get("baiduId"), msgModelAndroid);

        } catch (Exception exception) {
            reevesMap.setCode(500);
            reevesMap.setInfo("Error Occurred During Analyze The JsonObject.");
        }
        return net.sf.json.JSONObject.fromObject(reevesMap).toString();
    }

    @Override
    public String delReply(int userId, int replyId) {
        ReevesMap reevesMap = new ReevesMap();
        boolean result = feedDao.delReply(userId, replyId);

        if (result == false) {
            reevesMap.setCode(500);
            reevesMap.setInfo("Error Occurred During Delete The Reply");
        }
        reevesMap.put("result", result);
        return reevesMap.toJsonString();
    }

    @Override
    public String addPraise(int feedId, int userId) {
        ReevesMap reevesMap = new ReevesMap();
        reevesMap.put("result", feedDao.addPraise(feedId, userId));

        Map<String, Object> replyPushInfo = feedDao.praisePushInfo(userId, feedId);
        // 给IOS用户发送消息
        MsgModelIOS msgModelIOS = new MsgModelIOS();
        msgModelIOS.setAlertStr(replyPushInfo.get("name") + "赞了你的评论");
        msgModelIOS.put("type", "praiseReply");
        msgModelIOS.put("feedId", feedId);
        BaiduPush.pushMsgToSingleDeviceIOS((String) replyPushInfo.get("baiduId"), msgModelIOS);

        // 给Android用户发送消息
        MsgModelAndroid msgModelAndroid = new MsgModelAndroid();
        msgModelAndroid.setDescription(replyPushInfo.get("name") + "赞了你的评论");
        msgModelAndroid.custom_content.put("type", "praiseReply");
        msgModelAndroid.custom_content.put("feedId", feedId);
        BaiduPush.pushMsgToSingleDeviceAndroid((String) replyPushInfo.get("baiduId"), msgModelAndroid);

        return reevesMap.toJsonString();
    }

    @Override
    public String deletePraise(int feedId, int userId) {
        ReevesMap reevesMap = new ReevesMap();
        boolean result = feedDao.deletePraise(feedId, userId);

        if (result == false) {
            reevesMap.setCode(500);
            reevesMap.setInfo("No Data Found Or Delete");
        }
        reevesMap.put("result", result);
        return reevesMap.toJsonString();
    }

    @Override
    public String collectAdd(int feedId, int userId) {
        boolean result = feedDao.collectAdd(userId, feedId);
        ReevesMap reevesMap = new ReevesMap();
        if (result == false) {
            reevesMap.setCode(500);
            reevesMap.setInfo("Error Occurred During Record User Collect Feed");
        }
        reevesMap.put("result", result);
        return reevesMap.toJsonString();
    }

    @Override
    public String collect(int userId) {
        ReevesMap reevesMap = new ReevesMap();
        List<Map<String, Object>> result = feedDao.collect(userId);
        if (result == null) {
            reevesMap.setCode(500);
            reevesMap.setInfo("No More Data");
        } else {
            for (Map<String, Object> item : result) {
                item.replace("image", JSONArray.parse((String) item.get("image")));
                item.replace("voice", JSON.parseObject((String) item.get("voice")));
                item.replace("time", TimeFormat.monthDayHourMin(((Date) item.get("time")).getTime()));
            }
        }

        reevesMap.put("result", result);
        return reevesMap.toJsonString();
    }

    @Override
    public String report(int userId, int feedId) {
        ReevesMap reevesMap = new ReevesMap();
        boolean result = feedDao.report(userId, feedId);

        reevesMap.put("result", result);
        return reevesMap.toJsonString();
    }

    @Override
    public String collectDel(int feedId, int userId) {
        ReevesMap reevesMap = new ReevesMap();
        boolean result = feedDao.collectDel(userId, feedId);

        if (result == false) {
            reevesMap.setCode(500);
            reevesMap.setInfo("Error Occurred During Delete User Feed Collect");
        }
        reevesMap.put("result", result);
        return reevesMap.toJsonString();
    }

    @Override
    public String delete(int userId, int feedId) {
        ReevesMap reevesMap = new ReevesMap();
        boolean result = feedDao.delete(userId, feedId);

        if (result == false) {
            reevesMap.setCode(500);
            reevesMap.setInfo("Error Occurred During Delete The Feed");
        }
        reevesMap.put("result", result);
        return reevesMap.toJsonString();
    }
}
